package com.zlsx.androidutil.androidview.buttonview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zlsx.androidutil.R;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author zlsx
 * @time: 2019/8/26 11:06
 * @Description:
 **/
public class ButtonActivity extends AppCompatActivity {
    @BindView(R.id.progress_button)
    ProgressButton progressButton;
    @BindView(R.id.progress_bar)
    ProgressBarView progressBar;
    private int progress = 0;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case 0x01:
                    progressButton.updateProgress((int) message.obj);
                    progressButton.setText(String.format(getString(R.string.loading), (int) message.obj));
                    progressBar.setProgressSync((int) message.obj);
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button_view);
        ButterKnife.bind(this);
        initOnClick();
    }

    private void initOnClick() {
        progressButton.setOnClickListener(view -> {
            progress = 0;
            new Thread(() -> {
                while (progress < 100) {
                    try {
                        progress++;
                        handler.sendMessage(Message.obtain(handler, 0x01, progress));
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        });
    }
}
